from rest_framework.generics import CreateAPIView, UpdateAPIView, RetrieveUpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.question.models import Question
from . import serializer
from .models import User


# Create your views here.

class UserCrateView(CreateAPIView):
    """
    注册登录
    """
    serializer_class = serializer.CreateUserSerializer


class UserInfoView(RetrieveUpdateAPIView):
    """
    用户信息
    """
    permission_class = [IsAuthenticated]
    serializer_class = serializer.UserInfoSerializer

    def get_object(self):
        user = self.request.user
        replies = user.replies.all()
        user.answer_question = []
        for item in replies:
            if item.type == 2:
                user.answer_question.append(item)
        user.questions = []
        questions = Question.objects.filter(user=user)
        for question in questions:
            user.questions.append(question)

        return user


class UserLikeView(APIView):
    """
    设置关注
    """
    permission_class = [IsAuthenticated]

    # 关注
    def post(self, request, id):
        user = self.request.user
        idol = User.objects.get(id=id)
        if idol in user.idols.all():
            return Response({'message': '已关注过该用户', 'success': False}, status=400)
        user.idols.add(idol)
        user.save()
        return Response({'message': '关注成功', 'success': True})

    # 取消关注
    def delete(self, request, id):
        user = self.request.user
        idol = User.objects.get(id=id)
        if idol not in user.idols.all():
            return Response({'message': '未关注该用户', 'success': False}, status=400)
        user.idols.remove(idol)
        user.save()
        return Response({'message': '取消关注成功', 'success': True})


class UserPasswordView(UpdateAPIView):
    """
    修改密码
    """
    permission_class = [IsAuthenticated]
    serializer_class = serializer.UserPasswordSerializer

    def get_object(self):
        return self.request.user


class UserLabelView(UpdateAPIView):
    """
    修改用户标签
    """
    permission_classes = [IsAuthenticated]
    serializer_class = serializer.UserLabelSerializer

    def get_object(self):
        return self.request.user
